// 身份等群组信息 通过query查询
const express = require('express')
const router = express.Router()

const _Model = {
  allowance: require('../Model/Allowance'),
  tag: require('../Model/Tag'),
  family: require('../Model/Family')
}
const User = require('../Model/User')

const requiredOptions = {
  allowance: {
    name: '补助名称不能为空',
    creator: '创建失败，创建者不能为空'
  },
  tag: {
    name: '分类名称不能为空',
    creator: '创建失败: 创建者不能为空'
  },
  family: {
    user: '户主不能为空',
    creator: '创建失败: 创建者不能为空'
  },
  blank: {}
}

function handleMode(req, res, next) {
  const model = req.params.Model
  // 模型检查
  if (!Object.keys(_Model).includes(model)) {
    return res.hasError(404, '模型未找到')
  }
  next()
}

function handleRequire(model = 'blank', object = {}) {
  const option = requiredOptions[model]
  let error = []
  Object.keys(option).forEach((item) => {
    if (!object[item]) {
      error.push(option[item])
    }
  })
  return error.join('。 ')
}

router
  .get('/:Model', handleMode, (req, res, next) => {
    const model = req.params.Model
    const Model = _Model[model]
    const filters = req.filter
    /*
    * 使用说明:
    * 单个查询: model/single=yes&filter={"username: "^wivwiv"}&sort={"username": 1}
    * 多个查询: model/filter={"username": "^wivwiv"}&page=1&pageSize=100
    * 此处不返回下面的用户
    * */
    if (filters.single) {
      Model.findOne(filters.filter)
        .sort(filters.sort)
        .populate('creator', { username: 1 })
        .exec((err, doc) => {
          if (err) {
            req.handleFindError(err)
          } else {
            res.success(doc)
          }
        })
    } else {
      let total = 0
      Model.count((err, doc) => {
        total = parseInt(doc)
      })
      Model.find(filters.filter, filters.want)
        .sort(filters.sort)
        .populate('creator', { username: 1 })
        .limit(filters.pageSize)
        .skip((filters.page - 1) * filters.pageSize)
        .exec((err, doc) => {
          if (err) {
            req.handleFindError(err)
          } else {
            res.success({
              currentPage: filters.page,
              pageSize: filters.pageSize,
              totalPage: Math.ceil(total / filters.pageSize),
              data: doc,
              total: total,
            })
          }
        })
    }
  })

  .post('/:Model', handleMode, (req, res, next) => {
    const model = req.params.Model
    const Model = _Model[model]
    const data = req.body
    data.creator = req.user ? req.user._id : ''
    const error = handleRequire(model, data)
    if (error) {
      res.hasError(error)
    } else {
      Model.create(data, (err, doc) => {
        if (err) {
          return res.handleFindError(err)
        }
        res.success(doc)
      })
    }
  })

  // 更新成员不在这个接口
  .put('/:Model', handleMode, (req, res, next) => {
    const model = req.params.Model
    const Model = _Model[model]
    const data = req.body
    if (!data._id) {
      return res.hasError('操作对象为空')
    } else {
      // 防止注入
      delete data.user
      Model.findOneAndUpdate({ _id: data._id }, data)
        .exec((err, doc) => {
          if (err) {
            res.handleFindError(err)
          } else {
            res.success(data)
          }
        })
    }
  })

  .delete('/:Model/:_id', handleMode, (req, res, next) => {
    const model = req.params.Model
    const Model = _Model[model]
    const data = req.params._id
    console.log(data)
    if (!data) {
      return res.hasError('操作对象为空')
    } else {
      // 试着查找数据
      Model.findById(data)
        .exec((err, doc) => {
          if (!doc) {
            return res.hasError(404, '删除对象不存在')
          }
          User.count({}, (err, doc) => {
            if (!err && doc > 100) {
              res.hasError(500, '对象下面有用户未删除')
            } else if (err) {
              res.handleFindError(err)
            } else {
              Model.remove({ _id: data }, (err, doc) => {
                if (err) {
                  res.handleFindError(err)
                } else {
                  res.success('删除成功')
                }
              })
            }
          })
        })
    }
  })
module.exports = router